﻿
#include "wx/wx.h"
#include "MainForm.h"
#include "utils/audio/AudioUtils.h"

class ScopedPaHandler {
public:
    ScopedPaHandler() : _result(Pa_Initialize()) {}
    ~ScopedPaHandler() {
        if (_result == paNoError) {
            Pa_Terminate();
        }
    }

    PaError result() const { return _result; }

private:
    PaError _result;
};

class ScopedConsoleHandler {
public:
    ScopedConsoleHandler() {
        ::AllocConsole();
        freopen_s((FILE**)stdin, "CONIN$", "r", stdin);
        freopen_s((FILE**)stdout, "CONOUT$", "w", stdout);
        freopen_s((FILE**)stderr, "CONOUT$", "w", stderr);
    }

    ~ScopedConsoleHandler() {
        fclose(stdin);
        fclose(stdout);
        fclose(stderr);
        ::FreeConsole();
    }
};

class MyApp : public wxApp {
public:
    MyApp() = default;

    ~MyApp() {
        if (util::audio::IsAudioRecording()) {
            util::audio::StopAudioRecording();
        }
    }

    bool OnInit() override {
        if (!wxApp::OnInit()) {
            return false;
        }
        wxInitAllImageHandlers();
        // create main window
        auto frame = new MainForm(nullptr, 0, "WxComMonitor");
        SetTopWindow(frame);
        frame->Show(true);
        return true;
    }

private:
    ScopedPaHandler paHandler;
    //ScopedConsoleHandler consoleHandler;
};


wxIMPLEMENT_APP(MyApp);